//
//  MapSeachViewController.m
//  NewApp
//
//  Created by xueyan liu on 6/30/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MapSeachViewController.h"
#import "WebMapViewController.h"

#define ARC4RANDOM_MAX      0x100000000

@interface MapSeachViewController ()

@end

@implementation MapSeachViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    mapView.delegate = self;
    routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
    routeView.userInteractionEnabled = NO;
    [mapView addSubview:routeView];
    
    lineColor = [UIColor redColor];
    
    
    /*
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    CLLocationCoordinate2D centerCoordinate;
    centerCoordinate.latitude = 35.9097;
    centerCoordinate.longitude = 115.3476;
    MKCoordinateSpan span;
    span.latitudeDelta = 5;
    span.longitudeDelta = 5;
    MKCoordinateRegion region;
    region.center = centerCoordinate;
    region.span = span;
    //设置地图模式
    [mapView setRegion:region animated:TRUE];
    [mapView setMapType:MKMapTypeStandard];            //MKMapTypeHybrid卫星模式,MKMapTypeStandard标准模式,MKMapTypeSatellite云图(?)
    */

    [self.engine mapInfos];
    
    /*
    Place* p1 = [[[Place alloc] init] autorelease];
	p1.latitude = 24.157265;
	p1.longitude = 120.655922;
	
	Place* p2 = [[[Place alloc] init] autorelease];
	p2.latitude = 24.149842;
	p2.longitude = 120.655929;
	
	[self routeFrom:p1 to:p2];
    */
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) requestDidFinished:(RequestEngine *)reqEngine withObject:(id)object{

    startPlace = [[[Place alloc] init] autorelease];
    endPlace = [[[Place alloc] init] autorelease];
    if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *result = (NSDictionary *) object;
        [result retain];
        
        self.titleLabel.text = [result objectForKey:@"top_title"];
        NSString *latitude = [result objectForKey:@"lat"];
        NSString *longitude = [result objectForKey:@"lng"];
        startPlace.latitude = [latitude doubleValue];
        startPlace.longitude = [longitude doubleValue];
    }
    endPlace.latitude = 24.149842;
    endPlace.longitude = 120.655929;
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"搜索"
                                                                    style:UIBarButtonSystemItemDone target:self action:@selector(searchMap)];
    self.navigationItem.rightBarButtonItem = rightButton;
    //[rightButton release];
    
    [self routeFrom:startPlace to:endPlace];

}

-(void) searchMap{

    self.title = @"返回";
    WebMapViewController *webMapVctrl = [[WebMapViewController alloc] init];
    [self.navigationController pushViewController:webMapVctrl animated:YES];
    [webMapVctrl release];

}

-(void) routeFrom:(Place *)start to:(Place *)end{
	
	if(routes) {
		[mapView removeAnnotations:[mapView annotations]];
		[routes release];
	}
	
	PlaceMark* from = [[[PlaceMark alloc] initWithPlace:start] autorelease];
	PlaceMark* to = [[[PlaceMark alloc] initWithPlace:end] autorelease];
	
	[mapView addAnnotation:from];
	[mapView addAnnotation:to];
	
	routes = [[self calculateRoutesFrom:from.coordinate to:to.coordinate] retain];
	[self updateRouteView];
	[self centerMap];
}


-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {
	NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
	NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];
	
	NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
	NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
	NSLog(@"api url: %@", apiUrl);
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:nil];
	NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
	
	return [self decodePolyLine:[encodedPoints mutableCopy]];
}


-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
	[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
								options:NSLiteralSearch
								  range:NSMakeRange(0, [encoded length])];
	NSInteger len = [encoded length];
	NSInteger index = 0;
	NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
	NSInteger lat=0;
	NSInteger lng=0;
	while (index < len) {
		NSInteger b;
		NSInteger shift = 0;
		NSInteger result = 0;
		do {
			b = [encoded characterAtIndex:index++] - 63;
			result |= (b & 0x1f) << shift;
			shift += 5;
		} while (b >= 0x20);
		NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
		lat += dlat;
		shift = 0;
		result = 0;
		do {
			b = [encoded characterAtIndex:index++] - 63;
			result |= (b & 0x1f) << shift;
			shift += 5;
		} while (b >= 0x20);
		NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
		lng += dlng;
		NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
		NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
		printf("[%f,", [latitude doubleValue]);
		printf("%f]", [longitude doubleValue]);
		CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
		[array addObject:loc];
	}
	
	return array;
}

-(void) centerMap {
	MKCoordinateRegion region;
    
	CLLocationDegrees maxLat = -90;
	CLLocationDegrees maxLon = -180;
	CLLocationDegrees minLat = 90;
	CLLocationDegrees minLon = 180;
	for(int idx = 0; idx < routes.count; idx++)
	{
		CLLocation* currentLocation = [routes objectAtIndex:idx];
		if(currentLocation.coordinate.latitude > maxLat)
			maxLat = currentLocation.coordinate.latitude;
		if(currentLocation.coordinate.latitude < minLat)
			minLat = currentLocation.coordinate.latitude;
		if(currentLocation.coordinate.longitude > maxLon)
			maxLon = currentLocation.coordinate.longitude;
		if(currentLocation.coordinate.longitude < minLon)
			minLon = currentLocation.coordinate.longitude;
	}
	region.center.latitude     = (maxLat + minLat) / 2;
	region.center.longitude    = (maxLon + minLon) / 2;
	region.span.latitudeDelta  = maxLat - minLat;
	region.span.longitudeDelta = maxLon - minLon;
	
	[mapView setRegion:region animated:YES];
}


-(void) updateRouteView {
	CGContextRef context = 	CGBitmapContextCreate(nil, 
												  routeView.frame.size.width, 
												  routeView.frame.size.height, 
												  8, 
												  4 * routeView.frame.size.width,
												  CGColorSpaceCreateDeviceRGB(),
												  kCGImageAlphaPremultipliedLast);
	
	CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
	CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
	CGContextSetLineWidth(context, 3.0);
	
	for(int i = 0; i < routes.count; i++) {
		CLLocation* location = [routes objectAtIndex:i];
		CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:routeView];
		
		if(i == 0) {
			CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
		} else {
			CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
		}
	}
	
	CGContextStrokePath(context);
	
	CGImageRef image = CGBitmapContextCreateImage(context);
	UIImage* img = [UIImage imageWithCGImage:image];
	
	routeView.image = img;
	CGContextRelease(context);
    
}

#pragma mark mapView delegate functions
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
	routeView.hidden = YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
	[self updateRouteView];
	routeView.hidden = NO;
	[routeView setNeedsDisplay];
}


- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *pinView = nil;
    
    static NSString *defaultPinID = @"com.invasivecode.pin";
    pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
    if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
                                      initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
    pinView.pinColor = MKPinAnnotationColorRed;
    pinView.canShowCallout = YES;
    pinView.animatesDrop = YES;
    [mapView.userLocation setTitle:@"title"];
    [mapView.userLocation setSubtitle:@"content"];
    return pinView;
}

-(CLLocationCoordinate2D)locationMe{
    double lat = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 90.0f);
    double lng = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 180.0f);
    NSLog(@"(lat--->%f) (lng--->%f)",lat,lng);
    CLLocationCoordinate2D centerCoordinate;
    centerCoordinate.latitude = lat;
    centerCoordinate.longitude = lng;
    MKCoordinateRegion region;
    region.center = centerCoordinate;
    region.span = mapView.region.span;
    [mapView setRegion:region animated:TRUE];
    return centerCoordinate;
}


@end
